--
-- Author: yawei.zhu
-- Date: 2018-06-01 11:07:09
--
local NewRareInfoView = require("app.newBag.views.NewRareInfoView")
local NewBoxTipsView = require("app.newBag.views.NewBoxTipsView")
local Armature = app:getClass("Armature")

local PvpLadderBottom = class("PvpLadderBottom")

local STAR_ANI_GAP = 23

function PvpLadderBottom:ctor(node, parent)
	self._bottomNode = node
	self._parent = parent

	self:initNode()
end

function PvpLadderBottom:initNode()

	local bottom = self._bottomNode:getChildByName("Panel")
	self._starBar = bottom:findChild("bar_1/LoadingBar")
	self._starBar:setPercent(0)

	self._tipsMax = bottom:findChild("Panel_icon/tips_max")
	self._tlt = bottom:getChildByName("tlt_2")
	bottom:findChild("Panel_icon/lock"):setVisible(false)
	bottom:findChild("Panel_icon/mask"):setVisible(false)
	self._boxMask = bottom:findChild("Panel_icon/icon_2")
	self._boxMask:setVisible(true)
	self._boxMask:setTouchEnabled(true)
	display.uiAddClick(self._boxMask, function(sender, eventType)
		local dataTemp = GD:queryRestrictedRewardShowById( 3 )
		self:_showRareInfo( dataTemp, self._boxMask )
	end)

	self._boxPanel = bottom:getChildByName("Panel_icon")
	self._box = bottom:findChild("Panel_icon/icon")
	display.uiAddClick(self._box, function(sender, eventType)
		executeFunc(self._onOperate, "openBox")
	end, true)

	-- 宝箱动画
	self._boxTimeline = self._bottomNode:getTimeline()
	self._boxTimeline:gotoFrameAndPause(0)

	self._boxNumCon = self._boxPanel:getChildByName("bg_num")
	self._boxNumText = self._boxNumCon:getChildByName("num")

	-- 星星动画
	local starAniNode = bottom:findChild("bar_1/ani_championship")
	local timeline = cc.CSLoader:createTimeline(Res.PvpStarAniNode)
	starAniNode:runAction(timeline)
	timeline:gotoFrameAndPause(0)
	starAniNode:setVisible(false)
	self._starAniNode = starAniNode
	self._starAniPosX = starAniNode:getPositionX()
	self._starAni = timeline

	-- 等级相关
	self._levBar = bottom:findChild("bar_2/LoadingBar")
	self._levBar:setPercent(0)
	self._levText = bottom:getChildByName("num")
	self._expText = bottom:getChildByName("exp")

	local seasonlvBg = bottom:findChild("bar_2/bg1")
	display.uiAddClick(seasonlvBg, function(sender, eventType)
		self:_showBoxView(seasonlvBg)
	end)
end

function PvpLadderBottom:getBox()
	return self._boxPanel
end

-- 赛季奖励tips
function PvpLadderBottom:_showBoxView(triggerNode)

	local dataTemp = {
		name = L("seasonlv_name"),
		desc = L("seasonlv_des"),
		notice = L("tips_3000412")
	}
	local rewards = {}
	local level = tonumber(self._levText:getString())
	if level and level > 0 then
		local conf = GD:queryPvpSeasonConf(level)
		if conf then
			local dropIds = string.split(conf.seasonReward, ";")
			for _, dropId in ipairs(dropIds) do
				local rets = UD:parseDropIDToBagItem(dropId)
				if rets then
					for _, itemData in ipairs(rets) do
						table.insert(rewards, itemData)
					end
				end
			end
		end
	end
	dataTemp.rewards = rewards

	local rarePanel = NewBoxTipsView.create()
	rarePanel:setData(dataTemp)
	UIHandler:addPopupUi(rarePanel)

	-- 点击空白区域关闭
	display.nodeRemoveForNotHit(rarePanel, function()
		rarePanel:removeFromParent()
	end)

	local box = triggerNode:getBoundingBox()
	local worldPos = triggerNode:getParent():convertToWorldSpace( cc.p( box.x, box.y ) )
	box.x = worldPos.x
	box.y = worldPos.y
	display.adjustNodePos(box, rarePanel)
end

function PvpLadderBottom:_showRareInfo( dataTemp, triggerNode )
	if self._rareInfoPanel then
		self._rareInfoPanel:setData( dataTemp )
	else
		self._rareInfoPanel = NewRareInfoView.create()
		self._rareInfoPanel:setData( dataTemp )
		-- self._parent._ui["Panel"]:addChild( self._rareInfoPanel )
		UIHandler:addPopupUi(self._rareInfoPanel)

		-- 点击空白区域关闭
		display.nodeRemoveForNotHit(self._rareInfoPanel, function()
			if self._rareInfoPanel then
				self._rareInfoPanel:removeFromParent()
				self._rareInfoPanel = nil
			end
		end)
	end

	local box = triggerNode:getBoundingBox()
	local worldPos = triggerNode:getParent():convertToWorldSpace( cc.p( box.x, box.y ) )
	box.x = worldPos.x
	box.y = worldPos.y
	display.adjustNodePos( box, self._rareInfoPanel )
end

-- data = PvpInfo
function PvpLadderBottom:refresh(data, withAction)
	self._data = data
	withAction = withAction or false

	-- 有动画，动画结束来呈现
	if not withAction then
		if UD:onlyArenaLuckBoxChange() then
			UD:clearLuckBoxCacheByKey(Enums.lootType.arenaLuckBox)
			self._bottomNode:performWithDelay(function()
				self:_playBoxArmature()
			end, 0.05)
		end
		self:_refreshStar()
		self:_refreshLev()
	end
end

function PvpLadderBottom:_refreshStar(star, boxNum)
	if not star then
		star = self._data:getStar()
		boxNum = self._data:getBoxNum()
	end
	local maxAccumulateBoxNum = tonumber( GD:getSystemPar( "arenaBoxAccumulateLimited", 20 ) ) -- 累积的上限
	local hasBox = boxNum > 0
	local maxStar = UD:getLuckBoxLevelUpPoint(Enums.BoxType.pvp)
	self._starBar:setPercent((star / maxStar) * 100)
	self._boxMask:setVisible(not hasBox)
--	self._boxNumCon:setVisible(hasBox)
    self:_refreshNumBg(hasBox)
	self._tipsMax:setVisible( maxAccumulateBoxNum <= boxNum )
	self._tlt:setString(L("restrictedreward5_surface"))
	if hasBox then
		self._boxNumText:setString(boxNum)
		self._boxTimeline:gotoFrameAndPlay(0, true)
	else
		self._boxTimeline:gotoFrameAndPause(0)
	end
end

function PvpLadderBottom:_refreshLev()
	local season = self._data.seasonInfo
	local per, cur, max = season:getLevPercent()
	self._levBar:setPercent(per)
	self._levText:setString(season.lv)
	if per < 100 then
		self._expText:setString(string.format("%s/%s", cur, max))
	else
		self._expText:setString("MAX")
	end
end

function PvpLadderBottom:_refreshNumBg(isShow)
    local remainDayTimes = UD:getLuckBoxRestTimesByType(Enums.BoxType.pvp) --剩余每日开启次数
	local remainWeekTimes = UD:getLuckBoxWeeklyRestTimesByType(Enums.BoxType.pvp) -- 剩余每周开启次数
    local bgBlack = self._boxNumCon:getChildByName("bg_1")
    local bgRed = self._boxNumCon:getChildByName("bg")
    if isShow then
        if remainDayTimes > 0 and remainWeekTimes > 0 then
            bgRed:setVisible(true)
            bgBlack:setVisible(false)
        else
            bgRed:setVisible(false)
            bgBlack:setVisible(true)
        end
    end
    self._boxNumCon:setVisible(isShow)
end

-- 一整个经验条动画所需帧数
local FRAME_MAX = 30
local FRAME_MIN = 15

local curExp = 0
local nextExp = 0
local maxExp = 0
local curPer = 0
local nextPer = 0
local frameMax = 0
local frame = 0
local framePer = 0
local frameExp = 0

-- 播放宝箱特效
function PvpLadderBottom:_playBoxArmature()
	if not self._inArmature then
		local params = {
			armatureName = "shaizibengchu",
			path = Res.ChessRollInEfcPath
		}
		local armature = Armature.create(params)
		local posX, posY = self._boxPanel:getChildByName("Node_ani"):getPosition()
		self._boxPanel:addChild(armature)
		armature:setPosition(posX, posY)
		armature:setScale(0.3, 0.3)
		self._inArmature = armature
	end
	self._inArmature:setVisible(true)
	self._inArmature:play("shaizibengchu", 1, function(sender)
		sender:setVisible(false)
	end)
end

-- 播放change动画，有可能只有一个动画，有可能一个动画也没有，注意回调必须要调用
function PvpLadderBottom:playChangeAction(starData, stepDatas, cb)
	local isStarChange = starData[1] and starData[2] and starData[1] ~= starData[2]
	local isLevChange = #stepDatas > 0

	if isStarChange then
		local maxStar = tonumber(GD:getSystemPar("starpoint", 10))
		local boxNum = math.floor(starData[1] / maxStar)
		local starStart = starData[1] % maxStar
		local starEnd = starData[2] - boxNum * maxStar
		local starStartPer = starStart * 100 / maxStar
		local starEndPer = starEnd * 100 / maxStar
		local per = 2

		self:_refreshStar(starStart, boxNum)

		local function playStarBarAni()
			self._starBar:schedule(function()
					starStartPer = starStartPer + per
					if starStartPer == starEndPer then
						self._starBar:stopAllActions()
					else
						if starStartPer % 100 == 0 then
							-- 达到最大值，先停止动画，然后等星星动画结束，修改宝箱个数
							self._starBar:stopAllActions()
							self._starBar:setPercent(100)
						else
							self._starBar:setPercent(starStartPer % 100)
						end
					end
				end, 0.05)
		end

		-- star action
		local curStar = starStart + 1
		local function playStarAni(withDelay)
			local star = curStar
			local actions = {}
			if withDelay then
				actions[#actions + 1] = cca.delay(0.05 * maxStar)
				actions[#actions + 1] = cca.show()
			end
			actions[#actions + 1] = cca.cb(function()
					star = star % maxStar
					if star== 0 then
						star = 10
					end
					local posX = self._starAniPosX + (star - 1) * STAR_ANI_GAP
					self._starAniNode:setPositionX(posX)
					self._starAni:gotoFrameAndPlay(0, false)
					self._starAni:setTimeSpeed(2)
				end)

			local action = cca.seq(actions)
			self._starAniNode:runAction(action)
		end

		self._starAni:setLastFrameCallFunc(function()
				if curStar < starEnd then
					if curStar % maxStar == 0 then
						-- 星星到达最大数，先修改宝箱数量，再继续额外的动画
						boxNum = boxNum + 1
						self._boxNumText:setString(boxNum)
						self:_playBoxArmature() --播放一个获得宝箱的闪光特效
						if boxNum == 1 then
							self._boxMask:setVisible(false)
							-- self._boxNumCon:setVisible(true)
							self:_refreshNumBg(true)
							self._boxTimeline:gotoFrameAndPlay(0, true)
						end

						curStar = curStar + 1
						self._starAniNode:setVisible(false)
						playStarAni(true)
						playStarBarAni()
					else
						curStar = curStar + 1
						playStarAni()
					end
				else
					self._starAniNode:setVisible(false)
					self:_refreshStar()
					display.applySpriteShader(self._starBar:getVirtualRenderer():getSprite())

					executeFunc(cb, "star")
				end
			end)

		self._starBar:stopAllActions()
		display.applySpriteShader(self._starBar:getVirtualRenderer():getSprite(), "ShaderBrightness")
		playStarBarAni()

		playStarAni(true)
	else
		self:_refreshStar()
		executeFunc(cb, "star")
	end

	self._bottomNode:unscheduleUpdate()
	if isLevChange then
		self._compCB = cb
		display.applySpriteShader(self._levBar:getVirtualRenderer():getSprite(), "ShaderBrightness")

		self._stepDatas = stepDatas
		self._step = 0
		self:_nextStep()

		self._bottomNode:scheduleUpdate(handler(self, self._tick))
	else
		self:_refreshLev()
		executeFunc(cb, "level")
	end
end

function PvpLadderBottom:_stepOver()
	display.applySpriteShader(self._levBar:getVirtualRenderer():getSprite())
	self:_refreshLev()
	executeFunc(self._compCB, "level")
	self._compCB = nil
	self._stepDatas = nil
	self._bottomNode:unscheduleUpdate()
end

function PvpLadderBottom:_nextStep()
	self._step = self._step + 1

	-- 倒数第二步，结束
	if self._step == #self._stepDatas then
		self:_stepOver()
		return
	end

	local curData = self._stepDatas[self._step]

	self._levText:setString(curData.level)

	maxExp = curData.maxExp
	curExp = curData.exp
	nextExp = curData.nextExp

	if curExp == nextExp then
		self:_stepOver()
		return
	end

	curPer = curExp/maxExp * 100
	nextPer = nextExp/maxExp * 100
	frameMax = math.max(math.ceil(math.abs(nextPer - curPer) / 100 * FRAME_MAX), FRAME_MIN)
	framePer = (nextPer - curPer) / frameMax
	frameExp = (nextExp - curExp) / frameMax
	frame = 0
end

function PvpLadderBottom:_tick(dt)
	frame = frame + 1
	if frame < frameMax then
		local exp = curExp + math.round(frameExp * frame)
		self._expText:setString(string.format("%s/%s", exp, maxExp))
		self._levBar:setPercent(curPer + framePer * frame)
	elseif frame == frameMax then
		self._expText:setString(string.format("%s/%s", nextExp, maxExp))
		self._levBar:setPercent(nextPer)
		self:_nextStep()
	end
end

function PvpLadderBottom:onOperate(cb)
	self._onOperate = cb
end

return PvpLadderBottom

